/*
 * Created by Wildish on 2016-11-02
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hybridframework.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bm.library.PhotoView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wildish.hybridframework.R;
import com.wildish.hybridframework.core.HybridGlobal;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用photoview展示图片
 */
public class ViewPagerActivity extends Activity {

    private ViewPager mPager;
    private LinearLayout dotLayout;
    private ArrayList<PhotoView> photoViewList = new ArrayList<>();
    private List<View> dotViewsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);

        dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
        dotLayout.removeAllViews();

        mPager = (ViewPager) findViewById(R.id.pager);

        initData();
        fillData();
    }

    private void initData() {
        try {
            JSONArray imageArray = new JSONArray(getIntent().getStringExtra("imageList"));
            for (int i = 0; i != imageArray.length(); i++) {
                JSONObject image = imageArray.getJSONObject(i);
                String filePath = image.optString("url");
                Integer mode = image.optInt("mode", 1);
                PhotoView view = initPhotoView(filePath, mode);
                if(view != null) {
                    photoViewList.add(view);

                    ImageView dotView = new ImageView(this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
                    params.leftMargin = 8;
                    params.rightMargin = 8;
                    dotLayout.addView(dotView, params);
                    dotViewsList.add(dotView);
                }

            }

        } catch (Exception e) {
            HybridGlobal.logger.log(e);
        }
    }

    private void fillData() {
        for (int i = 0; i < dotViewsList.size(); i++) {
            if (i == 0) {
                ( dotViewsList.get(0)).setBackgroundResource(R.drawable.guide_focus_point);
            } else {
                ( dotViewsList.get(i)).setBackgroundResource(R.drawable.guide_blur_point);
            }
        }

        mPager.setPageMargin((int) (getResources().getDisplayMetrics().density * 15));
        mPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return photoViewList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(photoViewList.get(position));
                return photoViewList.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });

        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < dotViewsList.size(); i++) {
                    if (i == position) {
                        ( dotViewsList.get(position)).setBackgroundResource(R.drawable.guide_focus_point);
                    } else {
                        ( dotViewsList.get(i)).setBackgroundResource(R.drawable.guide_blur_point);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        int index =  getIntent().getIntExtra("index", 0);
        mPager.setCurrentItem(index);
    }

    private PhotoView initPhotoView(String filePath, Integer mode) {
        HybridGlobal.logger.log("初始化photoView：" + filePath + "模式mode:" + mode);
        PhotoView view = new PhotoView(ViewPagerActivity.this);
        view.enable();
        view.setScaleType(ImageView.ScaleType.FIT_CENTER);

        // 如果存在本地图片，则显示本地图片，如果不存在，则使用ImageLoader加载远程图片
        if(mode == 0) {
            if(new File(filePath).exists()) {
                view.setImageBitmap(getLocalBitmap(filePath));
            } else {
                view = null;
            }
        } else if(mode == 1) {
            ImageLoader.getInstance().displayImage(filePath, view);
        }
        return view;
    }

    private Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);

        } catch (Exception e) {
            HybridGlobal.logger.log(e);
            return null;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ViewPagerActivity.this.finish();
    }
}
